#include <cstdio>
#include <fstream>
#include <cstring>

#include "types.h"
#include "functions.h"

using namespace std;

// compute a score for a query
inline double scorequery(int arr[], int len)
{
	int i;
	double score = 0;
	for (i=0; i<len; ++i)
		score += ((double)(i+1)) / ((double)arr[i]);
	score /= (double)len;	// average
	return score;
}

// calculate precisions (or compute a score) for each query
void scoreClickFile(const char *clickfile, const char *locbinfile)
{
	printf(">>> score click file '%s' :\n", clickfile);

	char c;
	bool bin;
	printf("saved as a binary file? (Y/n) ");
	c = GetChar();
	if (c == 'n' || c == 'N')
		bin = false;
	else bin = true;

	ifstream cfin;
	ofstream fout;
	
	// we assume that all files can be opened successfully
	cfin.open(clickfile, ios::in);
	char *qsfile = NULL;
	if (bin)
	{
		formFilename(&qsfile, clickfile, QSBIN);
		fout.open(qsfile, ios::out | ios::binary);
	}
	else
	{
		formFilename(&qsfile, clickfile, QS);
		fout.open(qsfile, ios::out);
	}
	
	ClkLocList list;
	readlocs(&list, locbinfile);
	
	int posarr[MOSTCLICKS];	// array to save positions of all clicks of one query
	QueryScore qs;
	char curClick[CLICKLINESIZE];
	int i, t;
	if (!bin)	fout << "QueryID\tScore\n";
	
	for (t=0; t<list.size; ++t)
	{
		qs.ID = list.arr[t].ID;
		cfin.seekg(list.arr[t].location, ios::beg);
		for (i=0; i<list.arr[t].count; ++i)
		{
			cfin.getline(curClick, CLICKLINESIZE);
			int l = cfin.gcount();
			l--;
			while (curClick[l] != '\t')
				l--;
			sscanf(curClick + l + 1, "%d", &posarr[i]);
		}
		qs.score = scorequery(posarr, list.arr[t].count);
		if (bin) fout.write((const char *)(&qs), QSSIZE);
		else
		{
			char tmp[IDLEN + 1];
			uint642hexstr(qs.ID, tmp);
			fout << tmp << '\t'
				<< qs.score << endl;
		}

		if ((t+1) % PROGRESS == 0)
			printf("query %d\n", t+1);
	}
	printf(">>> score %d queries\n", list.size);
	printf(">>> score OK: file '%s' ==> file '%s'\n", clickfile, qsfile);
	cfin.close();
	fout.flush();
	fout.close();
	delete [] list.arr;
	delete [] qsfile;
}

void scoreCF()
{
	char *clickfiles[]={
		"srfp20060501-20060531.clicks.adult.txt",
		"srfp20060501-20060531.clicks.txt",
	};
	
	char c, b;
	char *locfile;
	printf("score click file:\n");
	printf("1: %s\n", clickfiles[0]);
	printf("2: %s\n", clickfiles[1]);
	printf("3: both 1 and 2\n");
	printf("0: exit\n");
	printf("choice: ");
	c = GetChar();
	switch (c)
	{
		case '3':
		case '1':	formFilename(&locfile, clickfiles[0], LOCBIN);
					scoreClickFile(clickfiles[0], locfile);
					if (c == '1') break;
					else
					{
						printf("Continue...(Y/n)? ");
						b = GetChar();
						if (b == 'n' || b == 'N')	break;
					}
		case '2':	formFilename(&locfile, clickfiles[1], LOCBIN);
					scoreClickFile(clickfiles[1], locfile);
		case '0':	break;
	}
}
